<template>
  <MenuPage 
  :columns="sceneCol" 
  :data="sceneList"
  :page.sync="querySceneInfo.pageIndex"
  :size.sync="querySceneInfo.pageSize"
  :total="totalCount"
  @queryFun="getSceneList">
    <template slot="search">
        <Input
          v-model.trim="querySceneInfo.sceneName"
          placeholder="请输入名称"
          style="width:180px;margin-right:10px"
          @on-change="debounceSearch()"
        ></Input>
        <Select filterable
          v-model.trim="querySceneInfo.type"
          placeholder="请选择类型"
          style="width:150px;"
          @on-change="changePage(1)"
        >
          <Option value="all">全部类型</Option>
          <Option v-for="item in showDrillAndCompete" :value="item.type" :key="item.name">{{item.title}}</Option>
          <!-- <Option :value="0" v-if="awdDrill">{{ awdDrill }}</Option>
          <Option :value="1" v-if="awdContest">{{ awdContest }}</Option>
          <Option :value="2" v-if="ctfContest">{{ ctfContest }}</Option>
          <Option :value="3" v-if="kcContest">{{ kcContest }}</Option>
          <Option :value="4" v-if="stDrill">{{ stDrill }}</Option>
          <Option :value="5" v-if="swDrill">{{ swDrill }}</Option>
          <Option :value="7" v-if="multipleDrill">{{ multipleDrill }}</Option>
          <Option :value="8" v-if="awdPlusContest">{{ awdPlusContest }}</Option> -->
          <!-- <Option :value="9" v-if="opContest">{{ opContest }}</Option> -->
          <!-- <Option :value="10" v-if="emergencyDefenseDrill">{{ emergencyDefenseDrill }}</Option>
          <Option :value="11" v-if="zcDrill">{{ zcDrill}}</Option>
          <Option :value="12" v-if="dailyDrill">{{ dailyDrill }}</Option> -->
          <!-- <Option :value="13" v-if="bigDrill">{{bigDrill}}</Option> -->
          <!-- <Option :value="14" v-if="hwDrill">{{hwDrill}}</Option> -->
        </Select>
        <!--<DatePicker :editable="false" type="datetimerange" v-model="querySceneInfo.Dates" format="yyyy-MM-dd HH:mm:ss" placement="bottom-start"
				    placeholder="选择回答过时间" style="width: 280px" transfer @on-change="timeChange"></DatePicker>-->
          <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refresh()"><i class="el-icon-refresh-right" /></Button>
   
    </template>
    <Modal v-model="loading" title="下载文件" width="300px" :mask-closable="false" footer-hide>
      <h3>
        <Icon
          type="ios-loading"
          size="24"
          class="demo-spin-icon-load"
          style="margin-right:24px;"
        ></Icon
        >文件下载中...
      </h3>
      <!--<Alert type="warning" show-icon style="margin-top:10px;">请勿离开此页面！！</Alert>-->
    </Modal>
</MenuPage>
</template>

<script>
import { getFilingList, delFiling, downloadFilingFile } from '@/api/drill_compete';
import encryption from '@/libs/encryption.js';
import TableTooltip from '@/view/drill_compete/page/tableTooltip.vue';
import { debounce } from '@/libs/utils'
let that = this;
export default {
  name: 'scenes',
  props: ['type'],
  components: {  },
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    const validateNum = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^([1-9]|[1-9]\\d|100)$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入1-100的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateDate = (rule, value, callback) => {
      //验证只能填入数字
      //var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
      //验证警戒值
      if (value) {
        if (
          (this.type == 0 || this.type == 1) &&
          new Date(value[1]).getTime() - new Date(value[0]).getTime() > 7 * 24 * 60 * 60 * 1000
        ) {
          callback(new Error('最长时间间隔为一周'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateIP = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp(
        '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
      );
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('ip格式错误'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      loading: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      projectid: '',
      W120: {
        width: '120px'
      },
      currentPage: 1,
      totalCount: 0,
      sceneList: [], //演练场景列表
      querySceneInfo: {
        pageIndex: 1,
        pageSize: 10,
        sceneId: this.$route.query.id,
        type: 'all'
      },
      sceneCol: [
        //        {
        //          type: 'index',
        //          align: 'center',
        //          ellipsis:true,
        //          width:50
        //        },
        {
          title: '名称',
          key: 'sceneName',
          align: 'center',
          ellipsis: true,
          placement: 'top-left',
          tooltip: true,
          width: 160
        },
        {
          title: '类型',
          key: 'type',
          placement: 'top-left',
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  width: '100px'
                }
              },
              this.typeFilter(params.row.type)
            );
          }
        },
        {
          title: '归档状态',
          key: 'deployStatus',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  type: 'border',
                  color: this.$options.filters.statusFilter(params.row.status, 'color')
                }
              },
              this.$options.filters.statusFilter(params.row.status, 'text')
            );
          }
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 200
        },
        {
          title: '开始时间',
          key: 'startTime',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 150
        },
        {
          title: '结束时间',
          key: 'endTime',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 150
        },
        {
          title: '归档人',
          key: 'creatorName',
          align: 'center',
          tooltip: true,
          width: 100
        },
        {
          title: '归档地址',
          key: 'address',
          align: 'center',
          tooltip: true,
          width: 80
        },
        {
          title: '归档路径',
          key: 'path',
          align: 'center',
          tooltip: true,
          width: 160
        },
        //		  {
        //		  	title:'录屏文件归档路径',
        //		  	key:'location',
        //		  	align:'center',
        //		  	width:300,
        //		  	tooltip:true,
        //		  	render:(h,params) => {
        //		  		return h('span',{
        //		  			props:{
        //
        //		  			}
        //		  		},params.row.type == 3  ? '-' : ('地址:172.18.0.25 路径:/opt/归档/'+params.row.sceneName))
        //		  	}
        //		  },
        {
          title: '归档时间',
          key: 'createTime',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 150,
          placement: 'top-left'
        },
        {
          title: '操作',
          key:'action',
          width: 120,
          opList:[
            {
              txt:'下载',
              disabled: (data) => {
                return data.status == 2 ? false : true
              },
              on: {
                click: (data,e) => {
                  this.loading = true;
                  this.downloadFilingFile(data.id, data.sceneName);
                }
              }
            },
            {
                txt: '删除',
                type: 'delete',
                tooltip: true,
                title: '你确定要删除吗?',
                disabled:(data) => {
                  return this.setReBtnStatus(data) || !this.isOwnData(data)
                },
                on: {
                  click: (data,e) => {
                    this.delFiling(data.id)
                  }
                }
            },
          ]
        }
      ]
    };
  },
  watch: {},
  filters: {
    statusFilter(val, type) {
      //0.新建、1.进行中、2完成、3失败
      let str = '',
        color = '';
      switch (val.toString()) {
        case '0':
          str = '新建';
          color = 'var(--status-pre)';
          break;
        case '1':
          str = '进行中';
          color = 'var(--status-ing)';
          break;
        case '2':
          str = '完成';
          color = 'var(--status-yes)';
          break;
        case '3':
          str = '失败';
          color = 'var(--status-no)';
          break;
        default:
          break;
      }
      return type == 'text' ? str : color;
    }
  },
  computed: {
    pageTitle () {
      //当前菜单显示名
      return this.$route.meta.title;
    },
    showDrillAndCompete(){
      return this.$store.getters.showDrillAndCompete;
    },
    emergencyDefenseDrill () { // 应急
       return this.$store.getters.getMenuName('emergencyDefenseDrill');
    },
    awdDrill () { // 对抗
       return this.$store.getters.getMenuName('awdDrill');
    },
    stDrill () { // 渗透
      return this.$store.getters.getMenuName('stDrill');
    },
    multipleDrill () { // 综合
      return this.$store.getters.getMenuName('multipleDrill');
    },
    hwDrill () { // 实网
      return this.$store.getters.getMenuName('hwDrill');
    },
    swDrill () { // 旧护网
      return this.$store.getters.getMenuName('swDrill');
    },
    awdContest () { // 攻防
      return this.$store.getters.getMenuName('awdContest');
    },
    awdPlusContest () { // 攻防Plus
      return this.$store.getters.getMenuName('awdPlusContest');
    },
    ctfContest () { // 夺旗
      return this.$store.getters.getMenuName('ctfContest');
    },
    opContest () { // 运维
      return this.$store.getters.getMenuName('opContest');
    },
    kcContest () { // 知识
      return this.$store.getters.getMenuName('kcContest');
    },
    zcDrill () { // 众测
      return this.$store.getters.getMenuName('zcDrill');
    },
    fzDrill () { // 仿真
      return this.$store.getters.getMenuName('fzDrill');
    },
    dailyDrill () { // 日常
      return this.$store.getters.getMenuName('dailyDrill');
    },
    bigDrill(){ // 大型
      return this.$store.getters.getMenuName('bigDrill');
    },
  },
  mounted () {
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    this._querySceneInfo = {...this.querySceneInfo};
    this.getSceneList();
  },
  beforeDestroy() {},
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      this.querySceneInfo.pageSize = Math.floor(this.setTableHei / 96);
    },
    typeFilter (val) {
      //0.对抗演练、1.攻防赛、2夺旗赛、3知识赛、4渗透演练
      let str = '';
      switch (val.toString()) {
        case '0':
          // str = '对抗演练';
          str = this.awdDrill;
          break;
        case '1':
          // str = '攻防赛';
          str = this.awdContest;
          break;
        case '2':
          // str = '夺旗赛';
          str = this.ctfContest;
          break;
        case '3':
          // str = '知识赛';
          str = this.kcContest;
          break;
        case '4':
          // str = '渗透演练';
          str = this.stDrill;
          break;
        case '5':
          // str = '护网演练';
          str = this.swDrill;
          break;
        case '6':
          // str = '应急防御演练';
          str = this.emergencyDefenseDrill;
          break;
        case '7':
          // str = '综合演练';
          str = this.multipleDrill;
          break;
        case '8':
          // str = '攻防赛Plus';
          str = this.awdPlusContest;
          break;
        case '9':
          // str = '运维赛';
          str = this.opContest;
          break;
        case '10':
          // str = '应急防御演练';
          str = this.emergencyDefenseDrill;
          break;
        case '11':
          // str = '众测VPN模式';
          str = this.zcDrill;
          break;
        case '12':
          // str = '日常渗透';
          str = this.dailyDrill;
          break;
        case '13':
          // str = '大型演练';
          str = this.bigDrill;
          break;
        case '14':
          // str = '实网测试';新护网
          str = this.hwDrill;
          break;
        case '15':
          // str = '实网测试';新护网
          str = this.fzDrill;
          break;  
        default:
          break;
      }
      return str;
    },
    statusFilter(val) {
      let str = '';
      switch (val) {
        case 0:
          str = '否';
          break;
        case 1:
          str = '是';
          break;
        default:
          break;
      }
      return str;
    },
    getSceneList() {
      let params = JSON.parse(JSON.stringify(this.querySceneInfo));
      params.type = params.type == 'all' ? '' : params.type;
      getFilingList(params)
        .then((data) => {
          if (data.code == 1) {
            this.sceneList = data.data.items;
            this.sceneList.forEach((item) => {
              let arr = item.location.split('  ');
              let address = arr[0].split('：')[1];
              let path = arr[1].split('：')[1];
              this.$set(item, 'address', address);
              this.$set(item, 'path', path);
            });
            this.totalCount = data.data.total;
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((err) => {
          this.$Message.error('获取归档列表失败，请稍后重试');
        });
    },
    debounceSearch:debounce(function(){
      this.changePage(1)
    },500),
    changePage(page) {
      this.querySceneInfo.pageIndex = page;
      this.getSceneList();
    },
    changeSize(size) {
      this.querySceneInfo.pageSize = size;
      this.getSceneList();
    },
    refresh(){
      this.querySceneInfo = {...this._querySceneInfo};
      this.getSceneList();
    },
    delScene(id) {
      delScene(id).then((data) => {
        if (data.code == 1) {
          this.getSceneList();
          this.$Message.info('操作成功');
        } else {
          this.$Message.error(data.message);
        }
      });
    },
    cancelLoading(modal) {
      modal.loading = false;
      setTimeout(() => {
        modal.loading = true;
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
      this.iconSrc = '';
      this.formValidate.iconPath = '';
      //      if(name=='assignePeople'){
      //        this.assignePeople = false;
      //      }
    },
    // 按钮点击状态
    setReBtnStatus(params) {
      if (params.status != 2 || params.status != 3) {
        return false;
      } else {
        return true;
      }
    },
    isOwnData(params) {
      if (params.creator === undefined || params.creator === this.USER_ID) {
        // 以前的数据，默认属于自己
        return true;
      }
      return false;
    },
    //删除归档文件
    delFiling(id) {
      delFiling(id)
        .then((data) => {
          if (data.code == 1) {
            this.getSceneList();
            this.$Message.info('操作成功');
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error('删除归档文件失败');
        });
    },
    downloadFilingFile(id, name) {
      downloadFilingFile(id)
        .then((data) => {
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = name + '.zip';
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('文件下载成功！');
          } else {
            this.$Message.error('下载失败!不存在文件数据！');
          }
          this.loading = false;
        })
        .catch((error) => {
          this.$Message.error('下载失败!');
          this.loading = false;
        });
    }
  },
  destroyed() {}
};
</script>
<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
